package com.mlh.filter;

import com.mlh.entity.LoginUser;
import com.mlh.utils.JwtUtil;
import com.mlh.utils.RedisCache;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

/**
 * @author 缪林辉
 * @date 2024/3/13 23:36
 * @DESCRIPTION
 */
@Component//注入该filter
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {
    @Autowired
    private RedisCache redisCache;
    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest,
                                    HttpServletResponse httpServletResponse,
                                    FilterChain filterChain) throws ServletException, IOException {
        //获取token
        String token = httpServletRequest.getHeader("token");
        if(!StringUtils.hasText(token)){
            //放行
            filterChain.doFilter(httpServletRequest, httpServletResponse);
            //为什么这里要return 因为doFilter方法执行完后，会返回继续执行下面的代码
            //这里涉及到filter的相关知识
            //直接return就不往下走了
            return;
        }
        // 解析token
        String userid;
        try {
            Claims claims = JwtUtil.parseJWT(token);
            userid = claims.getSubject();
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("token非法");
        }
        //从redis中获取用户信息
        String redisKey = "login:" + userid;
        //从之前的代码可知，存入到redis的用户信息是LoginUser对象
        //这里getCacheObject()使用了方法泛型，因此不需要强制转型
        LoginUser loginUser = redisCache.getCacheObject(redisKey);
        //redis也有可能没有存储 对应用户id的信息，说明此时token过期，需要重新登录
        if(Objects.isNull(loginUser)){
            throw new RuntimeException("用户未登录");
        }
        //将用户信息放入到SecurityContextHolder对象中，供后面的filter使用
        //这里必须用3个参数的构造器  因为构造器中调用super.setAuthenticated(true);
        //将用户设置成已认证的，后面的filter就是根据这个属性来认证该用户的
        //获取权限信息封装到Authentication中--->loginUser.getAuthorities()
        UsernamePasswordAuthenticationToken authenticationToken=
                new UsernamePasswordAuthenticationToken(loginUser,null,loginUser.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        //放行
        filterChain.doFilter(httpServletRequest, httpServletResponse);
    }
}
